import api from '@/api'
import store from '@/store'
import Cropper from 'cropperjs'

export const checkModifyBeforeLeave = {
  methods: {
    _checkModifyOrConfirm(modified, next) {
      if (modified) {
        this.$confirm('内容尚未保存，确定离开？', '提示', {
          type: 'warning'
        }).then(({ result }) => {
          if (result) {
            next()
          } else {
            next(false)
          }
        })
      } else {
        next()
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    this._checkModifyOrConfirm(this.modified, next)
  }
}

export const submitQuestion = {
  methods: {
    // 提交题目（外部调用）
    submitQuestion() {
      return this._submitQuestion(this.form, this.status)
    },
    // 提交题目
    async _submitQuestion(form, status) {
      var success = false
      if (status.submitting) {
        return
      }
      status.submitting = true
      try {
        if (!status.question) {
          await this._createQuestion(form, status)
        }
        if (!status.image && form.image !== null) {
          await this._uploadImage(form, status)
        }
        this.$toast.success('上传成功')
        success = true
      } catch (err) {
        this.$apiCatch(err)
      }
      status.submitting = false
      return success
    },
    // 上传题目
    async _createQuestion(form, status) {
      const { type_id, style, text, options, answer } = form
      const finalOptions = style === 0 ? options : []
      const { id } = await api.createQuestion(type_id, style, { text, options: finalOptions, answer })
      status.question = true
      status.id = id
      return id
    },
    // 上传图片
    async _uploadImage(form, status) {
      const { image } = form
      const autoClip = store.getters.questionCreateConfig.clip === 'auto'
      await api.uploadImage(status.id, { image }, autoClip)
      status.image = true
    }
  }
}

/**
 * 依赖
 * this.$refs[ref] 读
 * this[enable] 读
 * this[scope].cropper 读写
 * this[scope].result 读写
 * this[scope].width 写
 * this[scope].height 写
 */
export function buildCropper(config = {}) {
  const refName = config.ref || 'cropperImg'
  const enable = config.enable || true
  const scope = config.scope || 'cropper'
  const maxWidth = config.maxWidth || 512
  const maxHeight = config.maxHeight || 512
  const initRate = config.initRate || maxWidth / maxHeight || 1
  return {
    methods: {
      // 适当情况下初始化cropper
      initializeCropperWrapper() {
        if (enable === true || (typeof enable === 'string' && this[enable])) {
          this.$nextTick(() => {
            this.initializeCropper()
          })
        }
      },
      // 适当情况下销毁cropper
      destroyCropperWrapper() {
        if (this[scope].cropper !== null) {
          this.destroyCropper()
        }
      },
      // 初始化cropper
      initializeCropper() {
        this[scope].result = null
        const imageElement = this.$refs[refName]
        const cropper = new Cropper(imageElement, {
          initialAspectRatio: initRate,
          crop: ({ detail }) => {
            this[scope].width = detail.width
            this[scope].height = detail.height
          }
        })
        this[scope].cropper = cropper
      },
      // 销毁cropper
      destroyCropper() {
        this[scope].cropper.destroy()
        this[scope].cropper = null
      },
      // 重置cropper
      resetCropper() {
        this[scope].cropper.reset()
      },
      // 确定剪裁图片
      clipCropper() {
        this[scope].cropper.getCroppedCanvas({
          width: maxWidth, // 不知道为什么设置width和height能控制最大宽高，
          height: maxHeight, // 设置maxWidth和maxHeight反而控制不了
          // maxWidth: 512,
          // maxHeight: 340,
          fillColor: '#fff',
          imageSmoothingEnabled: true,
          imageSmoothingQuality: 'high'
        }).toBlob(data => {
          this[scope].result = data
          this.$toast.success('剪裁成功')
        })
      }
    }
  }
}
